#pragma once
#include<QMutex>
#include<QDateTime>
#include<QDir>


#if defined(Q_OS_WIN32)
const char* g_endSuffix = "\r\n";
#elif defined(Q_OS_LINUX)
const char* g_endSuffix = "\n";
#endif


void EnsureDir(QString path)
{
	QDir dir;
	if (!dir.exists(path)) {
		dir.mkdir(path);
	}
	return;
}


void messageHandle(QtMsgType type, const QMessageLogContext& context, const QString& msg)
{
	static QMutex mutex;
	QString logLevel;
	switch (type)
	{
	case QtDebugMsg:
		logLevel = QString("Debug");
		break;
	case QtWarningMsg:
		logLevel = QString("Warning");
		break;
		/*case QtCriticalMsg:
		logLevel = QString("Critical");
		break;*/
	case QtFatalMsg:
		logLevel = QString("Fatal");
		break;
	case QtInfoMsg:
		logLevel = QString("Info");
		break;
	case QtSystemMsg:
		logLevel = QString("System");
		break;
	default:
		break;
	}

	QString contextInfo = QString("File:(%1)Function:(%2)Line:(%3)").arg(QString(context.file)).arg(context.function).arg(context.line);
	//QString currentDateTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm::ss ddd");
	QString currentDateTime = QDateTime::currentDateTime().toString("hh:mm::ss");
	QString currentDate = QString("(%1)").arg(currentDateTime);
	QString message = QString("%1%2:%3%4").arg(logLevel).arg(contextInfo).arg(msg).arg(currentDate);

	QDateTime dateTime = QDateTime::currentDateTime();
	QString currentPath = QCoreApplication::applicationDirPath() + QString("/log");
	EnsureDir(currentPath);
	currentPath = currentPath + QString("/") + dateTime.toString("yyyy");
	EnsureDir(currentPath);
	currentPath = currentPath + QString("/") + dateTime.toString("MM");
	EnsureDir(currentPath);
	currentPath = currentPath + QString("/") + dateTime.toString("dd");
	EnsureDir(currentPath);
	mutex.lock();
	QFile logFile(currentPath + QString("/") + QString("xwater.log"));
	logFile.open(QIODevice::WriteOnly | QIODevice::Append);
	QTextStream textStream(&logFile);
	textStream << message << g_endSuffix;
	logFile.flush();
	logFile.close();
	mutex.unlock();
}
